package com.longrise.android.loaddata;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class MyRunnable implements Runnable {

    private static final String TAG = "MyRunnable";
    private final String mAppVersion;
    private final Context mContext;
    private int sendType;
    private ObserverCallBack callBack;
    private String url;
    private Map<String, String> map;
    private boolean isCache;
    private String resultString = null;
    private Handler handler = null;
    private HttpResponse httpResponse = null;

    public MyRunnable(Context context, String appVersion, int sendType, ObserverCallBack callBack,
                      String url, Map<String, String> map, boolean isCache) {
        this.mAppVersion = appVersion;
        this.sendType = sendType;
        this.callBack = callBack;
        this.url = url;
        this.map = map;
        this.isCache = isCache;
        this.mContext = context;
        handler = new Handler();
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        try {
            //1、创建请求对象
            HttpClient httpClient = new DefaultHttpClient();
            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
            switch (sendType) {
                case AnsynHttpRequest.GET:
                    HttpGet httpGet = new HttpGet(url);
                    if (null != LoadDataManager.getInstance(mContext).getCookie()) {
                        httpGet.addHeader("Cookie", LoadDataManager.getInstance(mContext).getCookie());
                    }
                    httpResponse = httpClient.execute(httpGet);
                    break;

                case AnsynHttpRequest.POST:
                    PrintLog.e("POST", "POST");
                    HttpPost httpPost = new HttpPost(url);
                    bbSetCookie(httpPost);
                    httpPost.addHeader("App-Version", mAppVersion);
                    httpPost.addHeader("Accept-Encoding", "gzip");
                    httpPost.addHeader("OSType", "android");
                    if (map != null) {
                        //封装传递参数的集合
                        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                        //往这个集合中添加你要传递的参数
                        for (String key : map.keySet()) {
                            parameters.add(new BasicNameValuePair(key, map.get(key)));
                        }
                        //创建传递参数封装 实体对象
                        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
                        //把实体对象存入到httpPost对象中
                        httpPost.setEntity(entity);
                    }
                    //xkj 添加请求开始时间戳
                    long startTime = System.currentTimeMillis();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date d1 = new Date(startTime);
                    String formatStartTime = format.format(d1);

                    //发送请求
                    httpResponse = httpClient.execute(httpPost);

                    //xkj 添加请求结束时间戳
                    long endTime = System.currentTimeMillis();
                    float needTime = ((float) (endTime - startTime)) / 1000;
                    String msg = needTime + "s :::" + formatStartTime + "::" + url;
                    String path = mContext.getExternalCacheDir().getPath() +
                            "/netWork.txt";

                    //xkj 这句话正式打包的时候要注释掉
                    //FileWriteUtil.writeFile(msg,path,true);
                    break;
            }

            //判断状态码
            if (200 == httpResponse.getStatusLine().getStatusCode()) {
                Header[] headers = httpResponse.getHeaders("Content-Encoding");

                //获取Cookid
                getCookies(httpResponse);
                //获取内容
                inputStream = httpResponse.getEntity().getContent();

                boolean isGzip = false;
                // 判断服务器有没有对数据进行gzip压缩
                if (headers.length > 0) {
                    for (Header header : headers) {
                        if ("gzip".equals(header.getValue())) {
                            isGzip = true;
                            break;
                        }
                    }
                }

                if (isGzip) {  //如果是压缩过的则解压
                    GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
                    resultString = streamToStr(gzipInputStream);
                } else {
                    resultString = streamToStr(inputStream);
                }

            }

        } catch (Exception e) {
            PrintLog.d(TAG, "EEE:" + e.toString());
            HttpHostConnectException
                    resultString = null;
        } finally {
            if (handler == null) {
                handler = new Handler();
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (null != callBack) {
                        //callBack.back(resultString, null);
                        callBack.back(resultString, null, httpResponse);
                        ThreadPoolUtils.remove(MyRunnable.this);
                    }
                }
            });


            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 登录 注册 相关的接口不能给接口设置cookie 先写死 以后换请求库
     */
    private void bbSetCookie(HttpPost httpPost) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        if (url.contains("bbt_login_sUserLogin") || url.contains("bbt_login_iUserReg")
                || url.contains("bbt_login_iUserRegByMobile") || url.contains("bbt_login_sUserLoginByMobile")) {
            return;
        }
        if (null != LoadDataManager.getInstance(mContext).getCookie()) {
            httpPost.addHeader("Cookie", LoadDataManager.getInstance(mContext).getCookie());
        }
    }

    /**
     * 把流对象转换成字符串对象
     *
     * @param is
     * @return
     */
    private String streamToStr(InputStream is) {
        try {
            // 定义字节数组输出流对象  
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            // 定义读取的长度  
            int len = 0;
            // 定义读取的缓冲区  
            byte buffer[] = new byte[1024];
            // 按照定义的缓冲区进行循环读取，直到读取完毕为止  
            while ((len = is.read(buffer)) != -1) {
                // 根据读取的长度写入到字节数组输出流对象中  
                os.write(buffer, 0, len);
            }
            // 关闭流  
            is.close();
            os.close();
            // 把读取的字节数组输出流对象转换成字节数组  
            byte data[] = os.toByteArray();
            // 按照指定的编码进行转换成字符串(此编码要与服务端的编码一致就不会出现乱码问题了，android默认的编码为UTF-8)  
            return new String(data, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取Cookie
     *
     * @param
     */
    private void getCookies(HttpResponse httpResponse) {
        org.apache.http.Header[] headers = httpResponse.getHeaders("Set-Cookie");
        if (headers == null) {
            return;
        }

        for (int i = 0; i < headers.length; i++) {
            String cookie = headers[i].getValue();
            String[] cookievalues = cookie.split(";");
            for (int j = 0; j < cookievalues.length; j++) {
                String[] keyPair = cookievalues[j].split("=");
                String key = keyPair[0].trim();
                //String value = keyPair.length > 1 ? keyPair[1].trim() : "";
                if (key != null) {
                    int index = key.indexOf("SESSIONID");
                    if (index >= 0) {
                        //LoadDataManager.getInstance(mContext).setCookie(cookievalues[j]);
                        saveCookie(cookievalues[j]);
                        return;
                    }

                }
            }
        }
    }

    /**
     * 保存cookie
     */
    private void saveCookie(String cookie) {
        if (!TextUtils.isEmpty(url)) {
//            //xkj 忘记密码的地方获取手机号不要存储cookie
//            if (url.endsWith("bbt_login_sUserInfoByNameOrCardno/query")) {
//                return;
//            }
//            //xkj LoadDataManager类中的这个上次日志的也要屏蔽掉
//            if (url.endsWith("bbt_setapplogs/query")) {
//                return;
//            }
//            //xkj 宝易的地址不要存储cookie
//            if (url.contains("restservices/web")) {
//                return;
//            }
            //只保存登录注册的cookie
            if (url.contains("bbt_login_sUserLogin") || url.contains("bbt_login_iUserReg")
                    || url.contains("bbt_login_iUserRegByMobile") || url.contains("bbt_login_sUserLoginByMobile")) {
                LoadDataManager.getInstance(mContext).setCookie(cookie);
            }
        }
    }
}
